#include "Packet.hpp"
#include "TLV.hpp"
Packet::Packet() 
: type(0), length(0), _msg("") 
{}

Packet::Packet(int t, int l, const string& m) 
: type(t), length(l), _msg(m) 
{}

Packet::~Packet() {};

void Packet::setType(int t) {
    type = t;
}

void Packet::setLength(int l) {
    length = l;
}

void Packet::setMsg(const std::string& m) {
    _msg = m;
}

Packet Packet::StringtoPacket(const std::string& tlvData) {
    // TLV数据前4字节是type，接下来4字节是length，后面是msg
    if (tlvData.size() < 8) {
        throw invalid_argument("Invalid TLV format: too short");//抛出异常
    }

    int type;
    memcpy(&type,tlvData.data(),sizeof(int));
    int length;
    memcpy(&length,tlvData.data() + 4,sizeof(int));

    if (tlvData.size() != 8 + length) {
        throw invalid_argument("Invalid TLV format: mismatched length");
    }

    string msg(tlvData.begin() + 8, tlvData.begin() + 8 + length);//从第9个字节截取length，保存为msg

    return Packet(type, length, msg);
}

TLV Packet::PackettoTLV(const Packet& PacketData){
    // 检查消息长度是否超过TLV缓冲区大小
    if (PacketData._msg.length() > 1023) {
        throw invalid_argument("Message too long for TLV");
    }
    
    // 创建并返回TLV对象
    return TLV(PacketData.type, PacketData.length, PacketData._msg);
}
